/*
 * @lc app=leetcode.cn id=54 lang=cpp
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
       
        vector<int> res;
        int row = matrix.size();        //行数
        int col = matrix[0].size();     //列数
        if(row == 0 || col == 0)
        {
            return res;
        }

        int left = 0;
        int right = col - 1;
        int top = 0;
        int bottom = row - 1;
        int numElement = row * col;

        while(left <= right && top <= bottom && numElement>=1)
        {
            for(int j = left ; j <= right && numElement >=1 ; j++)
            {
                res.push_back(matrix[top][j]);
                numElement--;
            }
            top++;


            for(int i = top;i <= bottom && numElement >= 1;i++)
            {
                res.push_back(matrix[i][right]);
                numElement--;
            }
            right--;
            
            for(int j = right ;j >= left && numElement >= 1;j--)
            {  
                res.push_back(matrix[bottom][j]);
                numElement--;
            }
            bottom--;
            
            for(int i = bottom ;i >= top && numElement >= 1; i--)
            {
                res.push_back(matrix[i][left]);
                numElement--;
            }
            left++;
        }
    return res;
    }
};
// @lc code=end

